package dao

import (
	"time"
	"xin-job/admin/dao/model"

	"gorm.io/gorm"
)

func SaveLog(jobLog *model.XxlJobLog) {
	db.Transaction(func(tx *gorm.DB) error {
		return tx.Create(jobLog).Error
	})
}

func UpdateLog(jobLog *model.XxlJobLog) {
	db.Transaction(func(tx *gorm.DB) error {
		return tx.Model(jobLog).Updates(jobLog).Error
	})
}

func LoadLog(logId int) *model.XxlJobLog {
	var r model.XxlJobLog
	db.First(&r, logId)
	return &r
}

func UpdateHandleInfoAndFinish(jobLog *model.XxlJobLog) {
	db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(jobLog).Updates(model.XxlJobLog{
			HandleTime: jobLog.HandleTime,
			HandleCode: jobLog.HandleCode,
			HandleMsg:  jobLog.HandleMsg,
		}).Error; err != nil {
			return err
		}

		return nil
	})
}

func FindLostJobIds(date time.Time) []int {
	var ids []int
	var sql = `	
		SELECT
			t.id
		FROM
			xxl_job_log t
			LEFT JOIN xxl_job_registry t2 ON t.executor_address = t2.registry_value
		WHERE
			t.trigger_code = 200
				AND t.handle_code = 0
				AND t.trigger_time  <= ?
				AND t2.id IS NULL`

	db.Raw(sql, date).Scan(&ids)

	return ids
}

func FindFailJobLogIds(pageSize int) []int {
	var ids []int
	var sql = `SELECT id FROM xxl_job_log
		WHERE !(
			(trigger_code in (0, 200) and handle_code = 0)
			OR
			(handle_code = 200)
		)
		AND alarm_status = 0
		ORDER BY id ASC
		LIMIT ?`
	db.Raw(sql, pageSize).Scan(&ids)
	return ids
}

func UpdateAlarmStatus(logId int, oldAlarmStatus int, newAlarmStatus int) int64 {
	var rowsAffected int64
	db.Transaction(func(tx *gorm.DB) error {
		result := tx.Model(&model.XxlJobLog{}).Where("id = ?", logId).Where("alarm_status", oldAlarmStatus).Select("alarm_status").Updates(model.XxlJobLog{AlarmStatus: newAlarmStatus})
		if result.Error != nil {
			return result.Error
		}

		rowsAffected = result.RowsAffected
		return nil
	})

	return rowsAffected
}

func UpdateTriggerInfo(jobLog *model.XxlJobLog) {
	db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(jobLog).Updates(model.XxlJobLog{
			TriggerTime:            jobLog.TriggerTime,
			TriggerCode:            jobLog.TriggerCode,
			TriggerMsg:             jobLog.TriggerMsg,
			ExecutorAddress:        jobLog.ExecutorAddress,
			ExecutorHandler:        jobLog.ExecutorHandler,
			ExecutorParam:          jobLog.ExecutorParam,
			ExecutorShardingParam:  jobLog.ExecutorShardingParam,
			ExecutorFailRetryCount: jobLog.ExecutorFailRetryCount,
		}).Error; err != nil {
			return err
		}

		return nil
	})
}
